import matplotlib.pyplot as plt
import numpy as np
import sys

# 折线图
def broken_line_graph():
    y1=[10,13,5,40,30,60,70,12,55,25] 
    x1=range(0,10) 
    x2=range(0,10) 
    y2=[5,8,0,30,20,40,50,10,40,15] 

    plt.plot(x1,y1,label='First line',linewidth=3,color='r',marker='o', 
        markerfacecolor='blue',markersize=12) 
    plt.plot(x2,y2,label='second line') 

    plt.xlabel('Plot Number') 
    plt.ylabel('Important var') 

    plt.title('Interesting Graph\nCheck it out') 
    plt.legend()  # show legend
    plt.show()
    #plt.savefig('metrics.png')

def bar_figure():
    y1=[10,13,5,40,30,60,70,12,55,25]
    x1=range(0,20,2)
    x2=range(1,21,2)
    y2=[5,8,0,30,20,40,50,10,40,15]
    plt.bar(x1,y1,label='First line')
    plt.bar(x2,y2,label='second line',color='r')

    plt.xlabel('Plot Number')
    plt.ylabel('Important var')

    plt.title('Interesting Graph\nCheck it out')
    plt.legend()
    plt.show()

def hist_figure():
    population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,
                   110,120,121,122,130,111,115,112,80,75,
                   65,54,44,43,42,48]
    x=range(0,130,10)

    # why y lies before x ?
    plt.hist(population_ages,x,rwidth=0.8,color='r',histtype='stepfilled')

    plt.xlabel('Plot Number')
    plt.ylabel('Important var')
    plt.title('Interesting Graph\nCheck it out')
    plt.legend()
    plt.show()

# python test.py /e/workspace/code-examples/bash/a.1
# 读pg-insert-latency后数据，发现在虚机里是有 hiccup的
def read_source_data_and_plot(filename):
    # comments='#' 可跳过读取, skiprows=1 可跳过行头; usecol 只选择哪些列
    # unpack=True 按列输出
    x, y = np.loadtxt(filename, delimiter=',', skiprows=1, unpack=True)
    N = len(x)
    x2 = np.arange(N)
    plt.plot(x2, y, label = 'metrics', linewidth=3, color='r',marker='o', 
        markerfacecolor='blue',markersize=6)
    #plt.xticks(x2, x)

    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('read data from txt')
    plt.legend()
    plt.show()

# 为johnny 性能优化图而定制, 这个函数为了对比均分x值与未均分时的差别
# https://johnnysswlab.com/the-memory-subsystem-from-the-viewpoint-of-software-how-memory-subsystem-effects-software-performance-1-2/
def read_source_data_and_compare_xaxis_equalRange_with_notEqual(filename):
    # comments='#' 可跳过读取, skiprows=1 可跳过行头; usecol 只选择哪些列
    # unpack=True 按列输出
    x, y = np.loadtxt(filename, delimiter=',', unpack=True)
    #print(x, '\n', y)
    N = len(x)
    xlabel = ['4K', '8K', '16K', '', '64K', '', '256K', '', '1M', '2M', '4M', '8M', '16M', '', '64M']
    x2 = np.arange(N)

    fig = plt.figure()
    plt.subplot(2, 1, 1)
    # 等间距
    plt.plot(x2, y, label = 'equal-x', linewidth=3, color='r', marker='o', markerfacecolor='blue', markersize=6)
    plt.xticks(x2, xlabel)
    plt.xlabel('array size')
    plt.ylabel('runtime(s)')
    plt.title('Time vs ArraySize')
    plt.legend()

    plt.subplot(2, 1, 2)
    plt.plot(x, y, label = 'non-equal-x')  # 非等间距
    plt.xticks(x, xlabel)
    plt.xlabel('array size')
    plt.ylabel('runtime(s)')
    plt.title('Time vs ArraySize')
    plt.legend()
    
    plt.show()
    #fig.savefig('xaxis-equalRange-VS-notEqual.png')

# 为johnny性能优化图而定制, 包含sum/div 
# 文件提取方式： egrep 'Region|, runtime ' a.txt | xargs -n2 -d '\n' | grep DIV | awk -F '[ _]' '{print $3 "," $13}'
#   或 egrep 'Region|, runtime ' a.txt | paste -d ' ' - - | grep DIV | awk -F '[ _]' '{print $3 "," $13}'
def read_source_data_and_plot_sumdiv_runtime(sumDataFile, divDataFile):
    # comments='#' 可跳过读取, skiprows=1 可跳过行头; usecol 只选择哪些列
    # unpack=True 按列输出
    sumX, sumY = np.loadtxt(sumDataFile, delimiter=',', unpack=True)
    divX, divY = np.loadtxt(divDataFile, delimiter=',', unpack=True)
    N = len(sumX)
    xlabel = ['4K', '8K', '16K', '', '64K', '', '256K', '', '1M', '2M', '4M', '8M', '16M', '', '64M']
    x2 = np.arange(N)

    plt.plot(x2, sumY, label = 'sum', linewidth=3, color='b')
    plt.plot(x2, divY, label = 'div', linewidth=3, color='r')
    plt.xticks(x2, xlabel)
    plt.xlabel('Array size')
    plt.ylabel('runtime(s)')
    plt.title('Time vs ArraySize')
    plt.legend()
    
    plt.grid(axis='y')
    plt.show()
    #plt.savefig('sum-div.png')

# https://stackoverflow.com/questions/28077499/matplotlib-pyplot-plot-x-axis-ticks-in-equal-range
# 由于x轴各点相差太大，如果直接画，看上去别扭（但真实），不过若各点等间距，看上去不真实
def make_xpoints_equal_range():
    x=[1,2,10,100,1000]
    y=[5,10,6,7,9]
    N = len(x)
    x2 = np.arange(N)
    # 设置画布，默认第一块画布
    plt.figure()
    plt.subplot(2, 1, 1)
    plt.plot(x2, y)  # 等间距
    plt.xticks(x2, x)
    plt.subplot(2, 1, 2)
    plt.plot(x, y)  # 非等间距
    plt.show()

def subplot():
    # 设置画布，默认第一块画布
    plt.figure()

    # 在2×2中选取第一块区域
    plt.subplot(2, 2, 1)
    plt.plot([0, 1], [0, 1])  # 绘制点线图[0,0]到[1,1]

    # 在2×2中选选取第二块区域
    plt.subplot(2, 2, 2)
    plt.plot([0, 1], [0, 2])  # 绘制点线图[0,0]到[1,2]

    # 在2×2中选选取第三块区域
    plt.subplot(2, 2, 3)
    plt.plot([0, 1], [0, 3])  # 绘制点线图[0,0]到[1,3]

    # 在2×2中选选取第四块区域
    plt.subplot(2, 2, 4)
    plt.plot([0, 1], [0, 4])  # 绘制点线图[0,0]到[1,4]

    plt.show()

def subplot_different_type():
    fig = plt.figure()
    ax1 = fig.add_subplot(2, 2, 1)
    ax2 = fig.add_subplot(2, 2, 2)
    ax3 = fig.add_subplot(2, 2, 3)
    ax4 = fig.add_subplot(2, 2, 4)

    # 在每个子图中进行绘图
    ax1.plot([1, 2, 3], [4, 5, 6])
    ax2.scatter([1, 2, 3], [4, 5, 6])
    ax3.bar([1, 2, 3], [4, 5, 6])
    ax4.pie([1, 2, 3])

    plt.show()

if __name__ == '__main__':
    n = sys.argv[1]
    if n == '1':
        make_xpoints_equal_range()
    elif n == '2':
        read_source_data_and_plot(sys.argv[2])
    elif n == '3':
        hist_figure()
    elif n == '4':
        bar_figure()
    elif n == '5':
        broken_line_graph()
    elif n == '6':
        read_source_data_and_compare_xaxis_equalRange_with_notEqual(sys.argv[2])
    elif n == '7':
        read_source_data_and_plot_sumdiv_runtime(sys.argv[2], sys.argv[3])
    elif n == '8':
        subplot_different_type()
    elif n == '9':
        subplot()